package com.dudu.utils;

import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Map;

/**
 * html相关工具类
 * 
 * @author zx
 *
 */
public class HtmlUtils {

	private static final String SCRIPT_START_TAG = "<script>";

	private static final String SCRIPT_END_TAG = "</script>";

	private static final String SCRIPT_IMPORT = "document.write(\"<script type='text/javascript' src=''{0}''></script>\");";

	private static final String ASSIGN_VALUE_STATEMENT = "var {0}=''{1}'';";

	private static final String HEX_CHARACTERS = "abcdef0123456789";

	private HtmlUtils() {

	}

	/**
	 * 生成js中的赋值语句
	 * 
	 * @param variables
	 *            传入map，键代表变量名称，值代表变量值
	 * @return
	 */
	public static String createAssignmentScript(Map<String, String> variables) {
		if (variables == null || variables.isEmpty())
			return "";
		StringBuilder script = new StringBuilder(variables.size() * 16);
		script.append("document.write(\"");
		script.append(SCRIPT_START_TAG);
		Iterator<String> iterator = variables.keySet().iterator();
		while (iterator.hasNext()) {
			String variableName = iterator.next();
			script.append(MessageFormat.format(ASSIGN_VALUE_STATEMENT,
					new Object[] { variableName, variables.get(variableName) }));
		}
		script.append(SCRIPT_END_TAG);
		script.append("\");");
		return script.toString();
	}

	/**
	 * 生成直接引入js文件的script语句
	 * 
	 * @param src
	 * @return
	 */
	public static String importScript(String[] src) {
		if (src == null || src.length == 0)
			return "";
		StringBuilder script = new StringBuilder(src.length * 16);
		for (int i = 0; i < src.length; i++) {
			script.append(MessageFormat.format(SCRIPT_IMPORT, new Object[] { src[i] }));
		}
		return script.toString();
	}
    
	/**
	 * 判断是否为十六进制的颜色值
	 * @param color
	 * @return
	 */
	public static boolean isHexadecimalColorValue(String color) {
		if (color.length() != 3 && color.length() != 6)
			return false;
		String[] colorList = color.toLowerCase().split("");
		for (int i = 0; i < colorList.length; i++) {
			if (HEX_CHARACTERS.indexOf(colorList[i]) == -1)
				return false;
		}
		return true;
	}

}
